<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      class="banner-form"
    >
      <!-- 基本信息 -->
      <div class="form-section">
        <div class="section-title">基本信息</div>
        
        <el-form-item label="横幅标题" prop="title">
          <el-input
            v-model="formData.title"
            placeholder="请输入横幅标题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="横幅描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            placeholder="请输入横幅描述（可选）"
            maxlength="200"
            show-word-limit
            :rows="3"
          />
        </el-form-item>

        <el-form-item label="横幅图片" prop="imageUrl">
          <UploadImg v-model="formData.imageUrl" :limit="1" />
          <div class="form-tip">建议尺寸：800x200px，支持jpg、png格式，大小不超过2MB</div>
        </el-form-item>
      </div>

      <!-- 链接设置 -->
      <div class="form-section">
        <div class="section-title">链接设置</div>
        
        <el-form-item label="链接类型" prop="linkType">
          <el-radio-group v-model="formData.linkType">
            <el-radio value="internal">内部页面</el-radio>
            <el-radio value="external">外部链接</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="跳转链接" prop="linkUrl">
          <el-input
            v-model="formData.linkUrl"
            :placeholder="formData.linkType === 'internal' ? '请输入内部页面路径，如：/pages/category/index' : '请输入完整的外部链接，如：https://www.example.com'"
            maxlength="500"
            show-word-limit
          />
          <div class="form-tip">
            <div v-if="formData.linkType === 'internal'">
              内部页面示例：/pages/category/index?category=special
            </div>
            <div v-else>
              外部链接示例：https://www.example.com
            </div>
          </div>
        </el-form-item>
      </div>

      <!-- 显示设置 -->
      <div class="form-section">
        <div class="section-title">显示设置</div>
        
        <el-form-item label="排序权重" prop="sortOrder">
          <el-input-number
            v-model="formData.sortOrder"
            :min="0"
            :max="9999"
            placeholder="数字越大越靠前"
            class="!w-200px"
          />
          <div class="form-tip">数字越大越靠前显示，默认为0</div>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="true">启用</el-radio>
            <el-radio :value="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="展示时间">
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item prop="startTime">
                <el-date-picker
                  v-model="formData.startTime"
                  type="datetime"
                  placeholder="开始时间（可选）"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="endTime">
                <el-date-picker
                  v-model="formData.endTime"
                  type="datetime"
                  placeholder="结束时间（可选）"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <div class="form-tip">不设置时间表示永久展示</div>
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm" :loading="formLoading">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import * as BannerApi from '@/api/reading/banner'

/** 横幅管理 表单 */
defineOptions({ name: 'BannerForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  title: '',
  description: '',
  imageUrl: '',
  linkUrl: '',
  linkType: 'internal',
  sortOrder: 0,
  status: true,
  startTime: undefined,
  endTime: undefined
})
const formRules = reactive({
  title: [{ required: true, message: '横幅标题不能为空', trigger: 'blur' }],
  imageUrl: [{ required: true, message: '横幅图片不能为空', trigger: 'blur' }],
  linkType: [{ required: true, message: '链接类型不能为空', trigger: 'change' }],
  sortOrder: [{ required: true, message: '排序权重不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '添加横幅' : '修改横幅'
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BannerApi.getBanner(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as BannerApi.BannerVO
    if (formType.value === 'create') {
      await BannerApi.createBanner(data)
      message.success(t('common.createSuccess'))
    } else {
      await BannerApi.updateBanner(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    title: '',
    description: '',
    imageUrl: '',
    linkUrl: '',
    linkType: 'internal',
    sortOrder: 0,
    status: true,
    startTime: undefined,
    endTime: undefined
  }
  formRef.value?.resetFields()
}

/** 关闭弹窗 */
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}
</script>

<style scoped lang="scss">
.banner-form {
  .form-section {
    margin-bottom: 24px;
    
    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 16px;
      padding-bottom: 8px;
      border-bottom: 1px solid #ebeef5;
    }
  }
  
  .form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
    line-height: 1.4;
  }
}
</style>
